<?php

namespace app\api\controller;

use app\api\service\message;
use app\common\model\tang\RepairMaterialLog;
use app\common\model\tang\RepairRecord as RecordModel;
use app\common\model\tang\RepairType;
use app\common\model\tang\RepairMaterial;
use app\common\model\tang\Merchant;
use think\facade\Db;
use app\common\model\tang\ReleaseUser;
use app\common\model\tang\Cost;
use think\facade\Log;

class RepairRecord extends Base
{
    /**
     * 获取维修工师傅
     */
    public function repairMan()
    {
        $result = (new ReleaseUser())->where('type', 2)->field('id,name')->select();
        if ($result->isEmpty()) {
            return SendSuccess('success', []);
        } else {
            return SendSuccess('success', $result);
        }
    }

    /**
     * 提交工单
     */
    public function addRecord()
    {
        $param = $this->request->param();
        if (empty($param['merchant_id']) || empty($param['repair_name']) || empty($param['repair_mobile'])||empty($param['repair_type_id'])) {
            return SendError('参数错误');
        }
        Db::startTrans();
        try {
            $record = new RecordModel();
            $recordInfo = $record->where($param)->whereTime('create_time', 'today')->find();
            if (!empty($recordInfo)) {
                return SendError('请勿重复提交');
            }
            $repairName = (new RepairType())->where('id', $param['repair_type_id'])->value('name');
            $param['order_sn'] = OrderSn();
            $param['create_time'] = time();
            $result = $record->insertGetId($param);
            if ($result) {
                //报修成功给分配工单的人推送消息
                $release = (new ReleaseUser())->where('is_sendmsg',1)->select();
                if(!empty($release)){
                    $release = $release->toArray();
                    foreach ($release as $k=>$v){
                        $sendInfo['openid'] =$v['openid'];
                        $sendInfo['name'] =$param['repair_name'];
                        $sendInfo['mobile'] = $param['repair_mobile'];
                        $sendInfo['repair_name'] = $repairName;
                        $sendInfo['reason'] = $param['describe'];
                        $ss = (new message())->send_release($sendInfo);
                        Log::record($ss,'--报修推送消息结果--');
                    }
                }
                Db::commit();
                return SendSuccess('报修成功', '');
            } else {
                return SendError('系统繁忙');
            }
        } catch (\Exception $exception) {
            Db::rollback();
            return SendError($exception->getMessage());
        }
    }

    /**
     * 获取报修相关信息
     */
    public function getInfo()
    {
        $RepairType = (new RepairType())->field('id,name')->order('id desc')->select();
        $RepairType[] = ['id'=>0,'name'=>'全部'];
        $data['typeList'] = $RepairType;
        $data['mobile'] = $this->getMobile();
        $merchant = (new Merchant)->field('id,name,username')->find($this->merchant_id);
        $merchantList = (new Merchant())->field('id,name,berth_number')->where('status',1)->where('mobile', $this->mobile)->select()->toArray();
        if(empty($merchantList)){ //说明是员工
            $merchantList = (new Merchant())->field('id,name')->where('status', 1)->where('id', $this->merchant_id)->select();
        }
        if (!empty($merchant)) {
            $data['name'] = $merchant['username'];
            $data['merchant_name'] = $merchant['name'];
            $data['merchant_id'] = $merchant['id'];
        }
        $data['merchantList'] = $merchantList;
        return SendSuccess('success', $data);
    }
    /**
     * 分配维修工
     */
    public function assignWorker()
    {
        $id = $this->request->param('id');
        $despose_id = $this->request->param('despose_id');
        if (empty($id) || empty($despose_id)) {
            return SendError('必填参数不能为空');
        }
        $desposeInfo = (new ReleaseUser())->where('id', $despose_id)->find();
        $recordInfo = RecordModel::find($id);
        if (empty($recordInfo)) {
            return SendError('该报修单不存在');
        }
        if ($recordInfo['status'] > 0) {
            return SendError('该订单已分配');
        }
        if($recordInfo['status']==0){
            $result = RecordModel::update(['status' => 1, 'dispose_id' => $desposeInfo['id'], 'dispose_name' => $desposeInfo['name'], 'order_time' => time()], ['id' => $id]);
        }else{
            $cost = Cost::field('id,pay_status')->find($recordInfo['cost_id']);
            if(!empty($cost)){
                if ($cost['pay_status'] == 0) {
                    return SendError('尚未支付维修费用,不能进行二次派单');
                }
            }
            $result = RecordModel::update(['status' => 5, 'dispose_id_sec' => $desposeInfo['id'],'order_time_sec' => time(), 'dispose_name_sec' => $desposeInfo['name']], ['id' => $id]);
        }
        if(isset($desposeInfo['openid'])){
            $repairName = (new RepairType())->where('id', $recordInfo['repair_type_id'])->value('name');
            $sendMaster['openid'] = $desposeInfo['openid'];
            $sendMaster['order_sn'] = $recordInfo['order_sn'];
            $sendMaster['repair_name'] = $repairName;
            $sendMaster['reason'] = $recordInfo['describe'];
            $sendMaster['name'] = $desposeInfo['name'];
            $sendMaster['time'] = date('Y-m-d');
            $message = (new message())->send_master($sendMaster);
            Log::record('-----维修师傅推送消息------','info');
            Log::record($message,'info');
        }

        if ($result) {
            return SendSuccess('success');
        } else {
            return SendError('系统繁忙');
        }
    }
    /**
     * 查看工单详情
     */
    public function recordDetail()
    {
        $id = $this->request->param('id');
        if (empty($id)) {
            return SendError('参数错误');
        }
        $recordInfo = RecordModel::with(['repairType' => function ($e) {
            $e->field('id,name')->find();
        }, 'merchant'])->where('id', $id)->find();
        if(!$recordInfo->isEmpty()){
            $recordInfo = $recordInfo->toArray();
            if(!empty($recordInfo['order_time'])){
                $recordInfo['order_time'] = date('Y-m-d H:i',$recordInfo['order_time']);
            }
            if(!empty($recordInfo['create_time'])){
                $recordInfo['create_time'] = date('Y-m-d H:i',$recordInfo['create_time']);
            }
            if(!empty($recordInfo['dispose_time'])){
                $recordInfo['dispose_time'] = date('Y-m-d H:i',$recordInfo['dispose_time']);
            }
        }
        if (!empty($recordInfo['images'])) {
            $recordInfo['images'] = explode(',', $recordInfo['images']);
        }
        if (!empty($recordInfo['dispose_image'])) {
            $recordInfo['dispose_image'] = explode(',', $recordInfo['dispose_image']);
        }
        if (!empty($recordInfo['dispose_material'])) {
            $material = explode(',', $recordInfo['dispose_material']);
            $allMoney = 0;
            foreach ($material as $k => $v) {
                $temp = explode(':', $v);
                $price = (new RepairMaterial())->field('id,price')->find($temp[0]);
                $singel = bcmul($price['price'], $temp[2], 2);
                array_push($temp, $singel);
                array_push($temp, $price['price']);
                $allMoney += bcmul($price['price'], $temp[2], 2);
                $material[$k] = $temp;
            }
            $workPriceInfo = (new RepairMaterial())->field('id,name,price')->find(1);
            $workPrice = bcmul($workPriceInfo['price'], $recordInfo['working_hours'], 2);
            $workItem[] = $workPriceInfo['id'];
            $workItem[] = $workPriceInfo['name'];
            $workItem[] = $recordInfo['working_hours'];
            $workItem[] = $workPrice;
            $workItem[] = $workPriceInfo['price'];
            $material[] = $workItem;
            $recordInfo['dispose_material'] = $material;
            $recordInfo['allMoney'] = bcadd($allMoney, $workPrice, 2);
        }
        //查询订单是否已支付
        if ($recordInfo['cost_id']) {
            $costInfo = Cost::field('id,pay_status')->find($recordInfo['cost_id']);
            if (empty($costInfo)) {
                $recordInfo['is_pay'] = 0;
            } else {
                $recordInfo['is_pay'] = $costInfo['pay_status'];
            }
        }
        $recordInfo['mobile'] = $this->getMobile();
        return SendSuccess('success', $recordInfo);
    }

    /**
     * 商户端获取报修列表
     */
    public function merchantRecordList()
    {
        $merchantId = $this->merchant_id;
        $status = $this->request->param('status');
        if (empty($merchantId)) {
            return SendError('参数错误');
        }
        $where[] = ['merchant_id', '=', $merchantId];
        if ($status != -1) {
            if ($status == 3) {
                $where[] = ['status', '>', 2];
            } else {
                $where[] = ['status', '=', $status];
            }
        }
        $list = RecordModel::with(['repairType' => function ($e) {
            $e->field('id,name')->find();
        }])->where($where)->field('id,repair_type_id,status,order_sn,describe,create_time,images')->order('id desc')->select();
        if(!$list->isEmpty()){
            $list = $list->toArray();
            foreach ($list as $key => $val) {
                if (!empty($val['images'])) {
                    $list[$key]['images'] = explode(',', $val['images']);
                }
                $list[$key]['create_time'] = date('Y-m-d H:i:s',$val['create_time']);
                if(!empty($val['order_time'])){
                    $list[$key]['order_time'] = date('Y-m-d H:i:s',$val['order_time']);
                }
                if(!empty($val['dispose_time'])){
                    $list[$key]['dispose_time'] = date('Y-m-d H:i:s',$val['dispose_time']);
                }
            }
        }
        return SendSuccess('success', $list);
    }

    /**
     * 商户端点已完成
     */
    public function complete()
    {
        $id = $this->request->param('id');
        if (empty($id)) {
            return SendError('参数错误');
        }
        $recordInfo = RecordModel::find($id);
        if (empty($recordInfo)) {
            return SendError('维修单不存在');
        }
        $cost = Cost::field('id,pay_status')->find($recordInfo['cost_id']);
        if ($cost['pay_status'] == 0) {
            return SendError('尚未支付维修费用');
        }
        $result = RecordModel::update(['status' => 3], ['id' => $id]);
        if ($result) {
            return SendSuccess('success');
        } else {
            return SendError('系统繁忙');
        }
    }

    /**
     * 管理端获取接单列表
     */
    public function recordList()
    {
        $repair_type_id = $this->request->param('repair_type_id');
        $status = $this->request->param('status');
        $where = [];
        if (!empty($repair_type_id)) {
            $where[] = ['repair_type_id', '=', $repair_type_id];
        }
        if ($status != -1) {
            $where[] = ['status', '=', $status];
        }
        $list = RecordModel::with(['repairType' => function ($e) {
            $e->field('id,name')->find();
        }])->field('id,repair_type_id,order_sn,describe,status,create_time,dispose_time')->where($where)->order('id desc')->select();
        if(!$list->isEmpty()){
            $list = $list->toArray();
            foreach ($list as $key => $val) {
                if (!empty($val['images'])) {
                    $list[$key]['images'] = explode(',', $val['images']);
                }
                $list[$key]['create_time'] = date('Y-m-d H:i:s',$val['create_time']);
                if(!empty($val['order_time'])){
                    $list[$key]['order_time'] = date('Y-m-d H:i:s',$val['order_time']);
                }
                if(!empty($val['dispose_time'])){
                    $list[$key]['dispose_time'] = date('Y-m-d H:i:s',$val['dispose_time']);
                }
            }
        }
        return SendSuccess('success', $list);
    }

    /**
     * 物业获取自己订单列表
     */
    public function masterList()
    {
        $mobile = $this->request->param('mobile');
        $status = $this->request->param('status');
        if (empty($mobile)) {
            return SendError('参数错误');
        }
        //查是否是管理人员
        $userInfo = ReleaseUser::where('mobile', $mobile)->find();
        if (empty($userInfo)) {
            return SendError('你不是维修人员');
        }
        $where[] = ['dispose_id', '=', $userInfo['id']];
        $whereor[] = ['dispose_id_sec', '=', $userInfo['id']];
        if ($status != -1) {
            $where[] = ['status', '=', $status];
        }
        $list = RecordModel::with(['repairType' => function ($e) {
            $e->field('id,name')->find();
        }, 'merchant'])->field('id,merchant_id,repair_type_id,order_sn,describe,status,create_time')->where($where)->whereOr($whereor)->order('id desc')->select();
        if (!$list->isEmpty()) {
            $list = $list->toArray();
            foreach ($list as $key => $val) {
                if (!empty($val['images'])) {
                    $list[$key]['images'] = explode(',', $val['images']);
                }
                $list[$key]['create_time'] = date('Y-m-d H:i:s', $val['create_time']);
                if (!empty($val['order_time'])) {
                    $list[$key]['order_time'] = date('Y-m-d H:i:s', $val['order_time']);
                }
                if (!empty($val['dispose_time'])) {
                    $list[$key]['dispose_time'] = date('Y-m-d H:i:s', $val['dispose_time']);
                }
            }
        }
        return SendSuccess('success', $list);
    }

    /**
     * 物业人员接单
     */
    public function maintainPick()
    {
        $mobile = $this->request->param('mobile');
        $id = $this->request->param('id');
        //查是否是管理人员
        $userInfo = ReleaseUser::where('mobile', $mobile)->find();
        if (empty($userInfo)) {
            return SendError('你不是维修人员');
        }
        $recordInfo = RecordModel::find($id);
        if (empty($recordInfo)) {
            return SendError('该报修单不存在');
        }
        if ($recordInfo['status'] > 0) {
            return SendError('该订单已有人接单');
        }
        $result = RecordModel::update(['status' => 1, 'dispose_id' => $userInfo['id'], 'dispose_name' => $userInfo['name'], 'order_time' => time()], ['id' => $id]);
        if ($result) {
            return SendSuccess('success');
        } else {
            return SendError('系统繁忙');
        }
    }

    /**
     * 物业人员退单
     */
    public function backRecord()
    {
        $mobile = $this->request->param('mobile');
        $id = $this->request->param('id');
        //查是否是管理人员
        $userInfo = ReleaseUser::where('mobile', $mobile)->find();
        if (empty($userInfo)) {
            return SendError('你不是维修人员');
        }
        $recordInfo = RecordModel::find($id);
        if ($recordInfo['status'] != 1) {
            return SendError('该订单不能退单了');
        }
        $result = RecordModel::update(['status' => 0, 'dispose_id' => Null, 'dispose_name' => Null, 'order_time' => Null], ['id' => $id]);
        if ($result) {
            return SendSuccess('success');
        } else {
            return SendError('系统繁忙');
        }
    }

    /**
     * 物业人员提交订单
     */
    public function submitRecord()
    {
        $mobile = $this->request->param('mobile');
        $id = $this->request->param('id');
        $dispose_material = $this->request->param('dispose_material');
        $dispose_result = $this->request->param('dispose_result');
        $dispose_image = $this->request->param('dispose_image');
        $working_hours = $this->request->param('working_hours');
        if (empty($id) || empty($dispose_material)) {
            return SendError('参数错误');
        }
        //查是否是管理人员
        $userInfo = ReleaseUser::where('mobile', $mobile)->find();
        if (empty($userInfo)) {
            return SendError('你不是维修人员');
        }
        $recordInfo = RecordModel::find($id);
        if (!empty($recordInfo['dispose_material'])) {
            return SendError('已经提交过了');
        }
        Db::startTrans();
        try {
            //计算价格生成订单
            $info = Db::name('cost_type')->find(48);
            //计算价格和税
            $material = explode(',', $dispose_material);
            $allMoney = 0;
            foreach ($material as $k => $v) {
                $temp = explode(':', $v);
                $price = (new RepairMaterial())->field('id,price')->find($temp[0]);
//                (new RepairMaterial())->where('id',$temp[0])->dec('score', $temp[2])->update();
                //物料用料记录
                $log['status'] = 2;
                $log['material_name'] = $temp[1];
                $log['material_id'] = $temp[0];
                $log['sum'] = $temp[2];
                $log['type'] = 1;
                $log['record_sn'] = $recordInfo['order_sn'];
                $log['operation_name'] = $userInfo['name'];
                (new RepairMaterialLog())->save($log);
                $allMoney += bcmul($price['price'], $temp[2], 2);
            }
            //计算工时费用
            if($allMoney>0){
                $workPriceInfo = (new RepairMaterial())->field('id,name,price')->find(1);
                $workPrice = bcmul($workPriceInfo['price'], $working_hours, 2);
                $allMoney = bcadd($allMoney, $workPrice, 2);
                $data['order_sn'] = OrderSn();
                $data['type'] = 6;
                $data['merchant_id'] = $recordInfo['merchant_id'];
                $data['cost_type_id'] = $info['id'];
                $data['pay_status'] = 0; //0未支付1已支付 -1已级退费
                $data['amount'] = $allMoney * 100 ;
                $data['real_amount'] =$allMoney * 100;
                $data['all_amount'] =$allMoney * 100;
                $data['service_charge'] = $allMoney * 100;
                $data['unit_price'] = 0;//交费单价
                $data['date_type'] = 2;//1时间区间2长期有效
                $data['is_admin_create'] = 1;//是否为人工创建1人工
                $data['create_time'] = time();
                $data['department_id'] = 6;//部门ID
                $cost_id = (new Cost())->insertGetId($data);
            }else{
                $cost_id = 0;
            }
            $result = RecordModel::update(['status' => 2, 'cost_id' => $cost_id, 'working_hours' => $working_hours, 'dispose_result' => $dispose_result, 'dispose_image' => $dispose_image, 'dispose_material' => $dispose_material, 'dispose_time' => time()], ['id' => $id]);
            if ($result) {
                Db::commit();
                return SendSuccess('success');
            } else {
                return SendError('系统繁忙');
            }
        } catch (\Exception $exception) {
            Db::rollback();
            return SendError($exception->getMessage());
        }
    }

    /**
     * 获取物料接口
     */
    public function getMaterial()
    {
        $RepairMaterial = (new RepairMaterial())->field('id,name,score,use_score')->where('id','>',1)->order('id desc')->select();
        return SendSuccess('success', $RepairMaterial);
    }

    /**
     * 生成表格价格
     */
    public function countPrice()
    {
        $dispose_material = $this->request->param('dispose_material');
        $working_hours = $this->request->param('working_hours');
        if (empty($dispose_material) || empty($working_hours)) {
            return SendError('参数错误');
        }
        if(!is_numeric($working_hours)){
            return SendError('工时必须为数字');
        }
        $material = explode(',', $dispose_material);
        $allMoney = 0;
        foreach ($material as $k => $v) {
            $temp = explode(':', $v);
            $price = (new RepairMaterial())->field('id,score,price')->find($temp[0]);
            if (!is_numeric($temp[2])||empty($temp[2])){
              return SendError($temp[1] . '数量必须为数字');
            }
            $singel = bcmul($price['price'], $temp[2], 2);
            array_push($temp, $price['price']);
            array_push($temp, $singel);
            $allMoney += bcmul($price['price'], $temp[2], 2);
            $material[$k] = $temp;
        }
        $workPriceInfo = (new RepairMaterial())->find(1);
        $workPrice = bcmul($workPriceInfo['price'], $working_hours, 2);
        $workItem[] = $workPriceInfo['id'];
        $workItem[] = $workPriceInfo['name'];
        $workItem[] = $working_hours;
        $workItem[] = $workPriceInfo['price'];
        $workItem[] = $workPrice;
        $material[] = $workItem;
        $recordInfo['dispose_material'] = $material;
        $recordInfo['allMoney'] = bcadd($allMoney, $workPrice, 2);
        return SendSuccess('success', $recordInfo);
    }
}